//
// Created by hjie on 23-6-11.
//

#include "media_process_client.h"
#include "./../../loop_event/loop_event_define.h"


MediaProcessClient::MediaProcessClient(LoopEvent *loop_event)
{
    m_loop_event = loop_event;
    m_media_process = std::make_shared<MediaProcess>("/home/hjie/source/study/FFmpeg/1.flv");
    m_status = false;
}

MediaProcessClient::~MediaProcessClient()
{
    if (m_thd.joinable())
    {
        m_thd.join();
    }
}

void MediaProcessClient::ChangeIpPort(const std::string &ip, uint16_t port)
{
    m_remote_ip   = ip;
    m_remote_port = port;
}

void MediaProcessClient::ProcessMediaData()
{
    m_status = true;
    m_media_process->StartReadThread();
    m_thd = std::thread([this](){

        //usleep(100 * 1000);
        m_udp_client = new UdpClient(m_loop_event, m_remote_ip, m_remote_port);
        m_udp_client->StartClient();
        int wait_time = 0;
        while(true)
        {
            AVPacket * packet = NULL;
            int result = m_media_process->GetAvPacket(&packet);
            if (result < 0)
            {
                if (result == -1 || EAGAIN == AVERROR(result))
                {
                    usleep(1000);
                    continue;
                }
                else
                {
                    printf("take to over %d\n", result);
                    break;
                }
            }
            m_udp_client->DoSendMsg(packet->data, packet->size);
            av_packet_free(&packet);
        }
        printf("wait time(ms) %d\n", wait_time);
    });
}
